package cn.wolfcode.web.advice;

import cn.wolfcode.qo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ClassName RuntimeExceptionHandler
 * Create by Mike
 * Date 2021/8/13 19:17
 */
@ControllerAdvice
public class RuntimeExceptionHandler {



    /*
    * 改方法是用来捕获某中异常的
    * e.现在出现的异常对象
    * method:现在出现异常的那个处理方法
    */
    @ExceptionHandler(RuntimeException.class)
    public String exceptionHandler(RuntimeException e, HandlerMethod method,
                                   Model model, HttpServletResponse response)throws Exception{
        //为方便开发时找bug
        e.printStackTrace();
        //若原本控制器的方法返回的是json,现在出异常页应该返回json
        //获取当前出现bug的方法,判断是否有response注解,有就代表需要返回json
        if (method.hasMethodAnnotation(ResponseBody.class)){
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSONString
                    (new JsonResult(false,"系统出问题了,我们的程序员正在加紧维修中!!!")));
            return null;
        }
        model.addAttribute("errorMsg","系统出问题了,我们的程序员正在加紧维修中!!!");
        //若原本控制器的方法时返回html,现在也应该返回html
        return "common/error";
    }

    @ExceptionHandler(UnknownAccountException.class)
    @ResponseBody
    public JsonResult handleUnknownAccountException(UnknownAccountException e){
        return new JsonResult(false,"用户名错误");
    }

    @ExceptionHandler(IncorrectCredentialsException.class)
    @ResponseBody
    public JsonResult handleIncorrectCredentialsException(IncorrectCredentialsException e){
        e.printStackTrace();
        return new JsonResult(false,"密码错误");
    }

    @ExceptionHandler(AuthorizationException.class)
    public String handleExceptionAuthorizationException
            (AuthorizationException e,Model model,HandlerMethod handlerMethod,HttpServletResponse response)
        throws IOException{
        e.printStackTrace();
        if (handlerMethod.getMethodAnnotation(ResponseBody.class) == null){
            //响应HTML
            //model.addAttribute("errorMsg","e.getMessage());
            return "common/nopermission";
        }else {
            //响应JSON
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(
                    JSON.toJSONString(new JsonResult(false,"对不起,您没有操作权限"))

            );
            return null;
        }
    }
}